<template>
  <div class="school-edit-container">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑学校' : '创建学校' }}</h2>
      <el-button @click="$router.push('/schools')">返回学校列表</el-button>
    </div>
    
    <el-card class="box-card">
      <el-form ref="schoolForm" :model="schoolForm" :rules="rules" label-width="100px">
        <el-form-item label="学校名称" prop="name">
          <el-input v-model="schoolForm.name" placeholder="请输入学校名称"></el-input>
        </el-form-item>
        
        <el-form-item label="学校代码" prop="code">
          <el-input v-model="schoolForm.code" placeholder="请输入学校代码"></el-input>
        </el-form-item>
        
        <el-form-item label="学校地址" prop="address">
          <el-input v-model="schoolForm.address" placeholder="请输入学校地址"></el-input>
        </el-form-item>
        
        <el-form-item label="学校Logo">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="uploadLogo"
            :show-file-list="false"
            :before-upload="beforeLogoUpload">
            <img v-if="schoolForm.logo" :src="schoolForm.logo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">推荐尺寸: 200 x 200</div>
        </el-form-item>
        
        <el-form-item label="学校描述" prop="description">
          <el-input type="textarea" v-model="schoolForm.description" :rows="4" placeholder="请输入学校描述"></el-input>
        </el-form-item>
        
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="schoolForm.contactPerson" placeholder="请输入联系人姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="schoolForm.contactPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="schoolForm.contactEmail" placeholder="请输入联系邮箱"></el-input>
        </el-form-item>
        
        <el-form-item label="学校状态">
          <el-radio-group v-model="schoolForm.status">
            <el-radio :label="0">未激活</el-radio>
            <el-radio :label="1">已激活</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getSchoolById, createSchool, updateSchool } from '@/api/school';
import { uploadFile } from '@/api/file';

export default {
  name: 'SchoolEdit',
  data() {
    return {
      isEdit: false,
      schoolId: null,
      loading: false,
      schoolForm: {
        name: '',
        code: '',
        address: '',
        logo: '',
        description: '',
        contactPerson: '',
        contactPhone: '',
        contactEmail: '',
        status: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入学校名称', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入学校代码', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        address: [
          { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
        ],
        description: [
          { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
          { max: 50, message: '长度不能超过 50 个字符', trigger: 'blur' }
        ],
        contactPhone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        ],
        contactEmail: [
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    // 判断是编辑还是创建
    if (this.$route.params.id) {
      this.isEdit = true;
      this.schoolId = this.$route.params.id;
      this.fetchSchoolDetail();
    }
  },
  methods: {
    fetchSchoolDetail() {
      if (!this.schoolId) return;
      
      this.loading = true;
      getSchoolById(this.schoolId)
        .then(response => {
          const { data } = response;
          if (data) {
            this.schoolForm = data;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    uploadLogo(options) {
      const { file } = options;
      this.loading = true;
      uploadFile(file)
        .then(response => {
          this.schoolForm.logo = response.data.url;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.$message.error('上传Logo失败');
        });
    },
    handleLogoSuccess(res, file) {
      // 实际项目中应该使用后端返回的URL
      this.schoolForm.logo = res.url || URL.createObjectURL(file.raw);
    },
    beforeLogoUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传Logo只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传Logo大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    submitForm() {
      this.$refs.schoolForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          
          const submitAction = this.isEdit 
            ? updateSchool(this.schoolForm) 
            : createSchool(this.schoolForm);
          
          submitAction
            .then(() => {
              this.$message({
                type: 'success',
                message: this.isEdit ? '学校更新成功!' : '学校创建成功!'
              });
              this.$router.push('/schools');
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.schoolForm.resetFields();
      if (this.isEdit) {
        this.fetchSchoolDetail();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.school-edit-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 22px;
      font-weight: bold;
    }
  }
  
  .avatar-uploader {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      
      &:hover {
        border-color: #409EFF;
      }
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 200px;
      height: 200px;
      line-height: 200px;
      text-align: center;
    }
    
    .avatar {
      width: 200px;
      height: 200px;
      display: block;
    }
  }
  
  .upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }
}
</style>